//
// Created by xunx on 2018/12/8.
//

#include "Sprite.h"
#include "Resource.h"
#include "Shader.h"
#include "Vertices.h"

Sprite::Sprite() {
    size = glm::vec2(40, 60);
    rotate = 0.0f;
    position = glm::vec2(0, 0);
    visible = true;

}

void Sprite::Draw() {
    if (visible) {
        Translate();
        glActiveTexture(GL_TEXTURE0);
        texture.Bind();
        glBindVertexArray(Resource::GetVertices("Sprite").GetVAO());
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr);
        glBindVertexArray(0);
    }
}

void Sprite::Translate() {
    glm::mat4 model = glm::mat4(1.0f);
    glm::mat4 projection = glm::mat4(1.0f);
    model = glm::translate(model, glm::vec3(position, 0.0f));
    model = glm::translate(model, glm::vec3(0.5f * size.x, 0.5f * size.y, 0.0f));
    model = glm::rotate(model, rotate, glm::vec3(0.0f, 0.0f, 1.0f));
    model = glm::translate(model, glm::vec3(-0.5f * size.x, -0.5f * size.y, 0.0f));
    model = glm::scale(model, glm::vec3(size, 1.0f));

    Resource::GetShader("Sprite").Use();
    Resource::GetShader("Sprite").SetMatrix4("model", model);

    projection = glm::ortho(0.0f, (float) SCR_WIDTH, (float) SCR_HEIGHT, 0.0f, -1.0f, 1.0f);
    Resource::GetShader("Sprite").SetMatrix4("projection", projection);

}

void Sprite::SetTexture(Texture2D texture) {
    this->texture = texture;
}

void Sprite::SetSize(float x, float y) {
    size = glm::vec2(x, y);
}

void Sprite::SetPosition(float x, float y) {
    position = glm::vec2(x, y);
}

void Sprite::SetRotate(float x) {
    rotate = x;
}

glm::vec2 Sprite::GetPosition() {
    return position;
}

glm::vec2 Sprite::GetSize() {
    return size;
}

float Sprite::GetRotate() {
    return rotate;
}


